﻿using QG.FrontDesk.com.Models;
using QG.FrontDesk.Model;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace QG.FrontDesk.com.Attbutes
{
    /// <summary>
    /// 权限过滤器
    /// </summary>
    public class PermissionAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool isAuthorized = false;
            if (DataContext<UserInfo>.context.model != null || DataContext<Company>.context.model != null)

            {
                isAuthorized = true;
            }
            else
            {
                //加载Cookie
                HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get("key");
                if (cookie != null)
                {
                    var username = cookie["key"];
                    if (DataContext<UserInfo>.context.model != null)
                    {
                        DataContext<UserInfo>.context.model = new Model.UserInfo() { UserName = username.ToString() };
                    }
                    else
                    {
                        DataContext<Company>.context.model = new Model.Company() { ComForShort = username.ToString() };
                    }
                    isAuthorized = true;
                }
            }

            return isAuthorized;
        }


        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string path = filterContext.HttpContext.Request.Path;
            //创建一个路由
            var route = new RouteValueDictionary { { "Controller", "Login" }, { "Action", "Login" }, { "ReturnUrl", path } };
            //跳转到指定路由
            filterContext.Result = new RedirectToRouteResult(route);
        }
    }
}